const service = require("../service/label.service")

const verifyLabelExists = async (ctx,next) => {
  //1.获取添加的所有的标签
  const {labels} = ctx.request.body;

  //2.判断每一个标签再label表中是否存在
  const labelList = []
  for (const name of labels) {
    const labelInfo = await service.getLabelByName(name)
    let label = {name}
    if(!labelInfo){
      // 创建标签数据
      const result = await service.create(name)
      label.id = result.insertId
    }else{
      label.id = labelInfo.id
    }
    labelList.push(label)
  }

  ctx.labels = labelList
  await next()
}

module.exports = {
  verifyLabelExists
}